package cn.xiongxf.mq.listener;

import cn.xiongxf.domain.PayFlow;
import cn.xiongxf.domain.PayOrder;
import cn.xiongxf.service.IPayOrderService;
import cn.xiongxf.util.AssertUtil;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.Map;

@RocketMQTransactionListener(txProducerGroup = "tx-producer-pay-result")
public class PayResultTxListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            AssertUtil.isNotNull(arg, "支付单数据无效！");
            Map<String, Object> map = (Map<String, Object>) arg;
            PayOrder payOrder = (PayOrder) map.get("payOrder");
            PayFlow payFlow = (PayFlow) map.get("payFlow");
            payOrderService.updateOrderAndFlow(payOrder, payFlow);

            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RocketMQLocalTransactionState.ROLLBACK;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return null;
    }
}
